package com.yyc.config;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.JSON;
import com.yyc.core.Result;
import com.yyc.core.ResultCode;
import com.yyc.core.ServiceException;
import com.yyc.interceptor.MyInterceptor;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	private final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);

	// 访问静态文件
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
		 super.addResourceHandlers(registry);
	}
	
	/**
	 * 该方法用于注册拦截器 可注册多个拦截器，多个拦截器组成一个拦截器链
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		super.addInterceptors(registry);
		// addPathPatterns 添加路径
		// excludePathPatterns 排除路径
		registry.addInterceptor(new MyInterceptor()).excludePathPatterns("/");
		// 有多个拦截器继续add进去，这里的拦截器只有经过DispatcherServlet 的请求，才会走拦截器链，默认不拦截静态资源
	}

	// 全局异常处理
	@Override
	public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
		System.out.println("-------------default error-------------------------------");
		exceptionResolvers.add((request, response, handler, e) -> {
			Result result = new Result();
			if (e instanceof ServiceException) {// 业务失败的异常，如“账号或密码错误”
				result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
				logger.info(e.getMessage());
			} else if (e instanceof NoHandlerFoundException) {
				result.setCode(ResultCode.NOT_FOUND).setMessage("接口 [" + request.getRequestURI() + "] 不存在");
			} else if (e instanceof ServletException) {
				result.setCode(ResultCode.FAIL).setMessage(e.getMessage());
			} else {
				result.setCode(ResultCode.INTERNAL_SERVER_ERROR)
						.setMessage("接口 [" + request.getRequestURI() + "] 内部错误，请联系管理员");
				String message;
				if (handler instanceof HandlerMethod) {
					HandlerMethod handlerMethod = (HandlerMethod) handler;
					message = String.format("接口 [%s] 出现异常，方法：%s.%s，异常摘要：%s", request.getRequestURI(),
							handlerMethod.getBean().getClass().getName(), handlerMethod.getMethod().getName(),
							e.getMessage());
				} else {
					message = e.getMessage();
				}
				logger.error(message, e);
			}
			responseResult(response, result);
			return new ModelAndView();
		});
	}

	private void responseResult(HttpServletResponse response, Result result) {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "application/json;charset=UTF-8");
		response.setStatus(200);
		try {
			response.getWriter().write(JSON.toJSONString(result));
		} catch (IOException ex) {
			logger.error(ex.getMessage());
		}
	}

}
